<?php

namespace app\admin\controller\repository;

use app\admin\logic\CategoryLogic;
use app\common\controller\Backend;
use think\Exception;

/**
 * Created by PhpStorm.
 * User: Orange
 * Date: 2018/4/26
 * Time: 10:00
 */

/**
 * 分类管理
 * Class Category
 * @package app\admin\controller\repository
 */
class Category extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Category');
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where(array('is_delete' => 0))
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->where(array('is_delete' => 0))
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post('row/a');
            if ($data) {
                $current_level = $data['current_level'];
                if ($current_level > 0) {
                    $parent_id = $data['category_id' . $current_level];
                    if (empty($parent_id)) {
                        $this->error('请选择父类别');
                    }
                } else {
                    $parent_id = 0;
                }
                $data['name'] = str_replace('）',')',$data['name'] );
                $data['name'] = str_replace('（','(',$data['name'] );
                $category_obj = model('Category')->where(array('name' => $data['name'], 'current_level' => $current_level))->where(array('is_delete' => 0))->find();
                if ($category_obj) {
                    $this->error('资料库中已存在该分类');
                }
                $category['parent_id'] = $parent_id;
                $category['current_level'] = $current_level;
                $category['name'] = $data['name'];
                $category['english_name'] = $data['english_name'];
                $category_obj = model('Category')->create($category);
                if ($category_obj) {
                    $this->success('添加成功');
                } else {
                    $this->error('添加失败');
                }
            }
            $this->error('添加失败');
        }
        return $this->view->fetch();
    }

    public function edit($ids = '')
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isAjax()) {
            $data = $this->request->post('row/a');
            if ($data) {
                $current_level = $data['current_level'];
                if ($current_level > 0) {
                    $parent_id = $data['category_id' . $current_level];
                    if (empty($parent_id)) {
                        $this->error('请选择父类别');
                    }
                } else {
                    $parent_id = 0;
                }
                $category['parent_id'] = $parent_id;
                $category['current_level'] = $current_level;
                $data['name'] = str_replace('）',')',$data['name'] );
                $data['name'] = str_replace('（','(',$data['name'] );
                $category['name'] = $data['name'];
                $category['english_name'] = $data['english_name'];
                $category_obj = model('Category')->where(array('name' => $data['name'], 'current_level' => $current_level))->where(array('is_delete' => 0))->find();
                if ($category_obj) {
                    $this->error('资料库中已存在该分类');
                }
                $row->save($category);
                $this->success('修改成功');
            }
            $this->error('修改失败');
        }
        $this->getParentCategory($row);
        $this->assignconfig('category', $row);
        return $this->view->fetch();
    }

    private function getParentCategory(&$row)
    {
        $current_level = $row['current_level'];
        $parent_id = $row['parent_id'];
        for (; $current_level > 0; $current_level--) {
            $parent = model('Category')->where(array('id' => $parent_id))->field('id,parent_id')->find();
            $parent_id = $parent['parent_id'];
            $row['category_id' . $current_level] = $parent['id'];
        }
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            try {
                $category = $this->model->where(array('parent_id' => $ids))->find();
                if ($category) {
                    $this->error('删除失败，存在关联分类数据');
                } else {
                    $bacteria = model('BacteriaCategory')->where(array('category_id' => $ids))->select();
                    foreach ($bacteria as $key => &$value) {
                        $isUse = model('Bacteria')->where(array('id' => $value['bacteria_id']))->value('is_use');
                        if ($isUse != 0) {
                            $this->error('删除失败,存在关联菌种数据');
                        }
                    }
                    $this->model->where(array('id' => $ids))->update(array('is_delete' => 1));
                    $this->model->where(array('id' => $ids))->update(array('parent_id' => 0));
                    $this->success('删除成功');
                }
            } catch (Exception $e) {
                $this->error('删除失败');
            }
        }
        $this->error();
    }

    /**
     * 批量导入
     */
    public function import()
    {
        ignore_user_abort();
        set_time_limit(0);
        $file = $this->request->file('file');
        if ($file) {
            $fileInfo = $file->getInfo();
            $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
            $suffix = $suffix ? $suffix : 'file';
            if (!in_array($suffix, ['xls', 'xlsx'])) {
                $this->error('请上传Excel文件！');
            }
            $path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel';
            if (!is_dir($path)) {
                mkdir($path, 0755, true);
            }
            $info = $file->move($path);
            if ($info) {
                $logic = new CategoryLogic();
                $file_path = ROOT_PATH . 'public/uploads/excel/' . $info->getSaveName();
                $result = $logic->import($file_path);
                unlink($file_path);//删除文件
                $msg = '';
                $success = false;
                $rtnData = array();
                switch ($result['status']) {
                    case 0:
                        $msg = $result['msg'];
                        break;
                    case 1:
                        $success = true;
                        break;
                    case 2:
                        $msg = $result['msg'];
                        break;
                }
                if ($success) {
                    $this->success('导入成功！');
                } else {
                    $this->error($msg, '', $rtnData);
                }
            } else {
                // 上传失败获取错误信息
                $this->error($file->getError());
            }
        } else {
            $this->error('文件不存在！');
        }
    }

    /**
     * 批量上传
     */
    public function upload_lower_level($ids = "")
    {
        $file = $this->request->file('file');
        if ($file) {
            $fileInfo = $file->getInfo();
            $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
            $suffix = $suffix ? $suffix : 'file';
            if (!in_array($suffix, ['xls', 'xlsx'])) {
                $this->error('请上传Excel文件！');
            }
            $path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel';
            if (!is_dir($path)) {
                mkdir($path, 0755, true);
            }
            $info = $file->move($path);
            if ($info) {
                $logic = new CategoryLogic();
                $file_path = ROOT_PATH . 'public/uploads/excel/' . $info->getSaveName();
                $result = $logic->importWithCategoryId($file_path, $ids);
                unlink($file_path);//删除文件
                $msg = '';
                $success = false;
                $rtnData = array();
                switch ($result['status']) {
                    case 0:
                        $msg = $result['msg'];
                        break;
                    case 1:
                        $success = true;
                        break;
                    case 2:
                        $msg = $result['msg'];
                        break;
                }
                if ($success) {
                    $this->success('导入成功！');
                } else {
                    $this->error($msg, '', $rtnData);
                }
            } else {
                // 上传失败获取错误信息
                $this->error($file->getError());
            }
        } else {
            $this->assignconfig('category_id', $ids);
            return $this->view->fetch();
        }
    }
}